import Vue from 'vue';
// #ifdef H5
let jweixin1 = require('jweixin-module')
	// #endif

/**
 * @author 晨昱
 * @param {Object} price 价格
 * @return {String} num
 */
Vue.prototype.jprice = function(price) {
	let num = Math.round((price * 100)) / 100;
	if (!(num + "".split('.')[1])) {
		return num.toFixed(2);
	} else {
		return num + "";
	}
};


Vue.prototype.$isWx = function() {
	// #ifdef H5
		let en = window.navigator.userAgent.toLowerCase()
		// 匹配en中是否含有MicroMessenger字符串
		if (en.match(/MicroMessenger/i) == 'micromessenger') {
			return true
		}
		// #endif
		return false
	},

	/**
	 * @return {String} price 
	 * @return {type} 类型，默认是没除100的
	 */
	Vue.prototype.$splitPrice = function(price, type) {
		let num
		let returnArray = []
		console.log(price)
		if (price == null) {
			returnArray[0] = '~'
			returnArray[1] = ''
			return returnArray
		}
		if (type) {
			num = (price * 1).toFixed(2) + '';
		} else {
			num = (price / 100).toFixed(2) + '';
		}
		let array = num.split('.')

		if (array.length > 1) {
			returnArray[0] = array[0]
			returnArray[1] = '.' + array[1]
		} else {
			returnArray[0] = array[0]
			returnArray[1] = ''
		}
		return returnArray;
	};

/**
 * @author 晨昱
 * 不成功的轻提示
 */
Vue.prototype.$noTost = function(title) {
	let image = "/static/images/public/warn.png"
	let icon = "none";
	if (title.length > 7) {
		image = "";
	}
	uni.showToast({
		title,
		icon,
		image,
		mask: true
	})
}

Vue.prototype.$noIconTost = function(title) {
	let icon = "none";
	uni.showToast({
		title,
		icon,
	})
}

Vue.prototype.$nullToZero = function(param) {
	if (param == null) {
		return 0
	}
	return param;
};

/**
 * @author 晨昱
 * @param {Object} timestamp 时间戳
 * 服务端时间戳转日期
 */
Vue.prototype.timestamp = function(timestamp) {
	console.log(timestamp)
	let d = new Date(timestamp * 1000); //根据时间戳生成的时间对象
	let year = d.getFullYear();
	let month = d.getMonth() + 1;
	if (month < 10) {
		month = "0" + month
	}
	let date = d.getDate();
	if (date < 10) {
		date = "0" + date
	}
	let hours = d.getHours();
	if (hours < 10) {
		hours = "0" + hours
	}
	let minutes = d.getMinutes();
	if (minutes < 10) {
		minutes = "0" + minutes
	}
	let seconds = d.getSeconds();
	if (seconds < 10) {
		seconds = "0" + seconds
	}
	let dateTime = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds
	console.log(dateTime)
	return dateTime;
};

/**
 * @author 晨昱
 * @param {Object} timestamp 时间戳
 * js生成的时间戳转日期
 */
Vue.prototype.jstimestamp = function(timestamp) {
	console.log(timestamp)

	let d = new Date(timestamp * 1000); //根据时间戳生成的时间对象
	let year = d.getFullYear();
	let month = d.getMonth() + 1
	if (month < 10) {
		month = "0" + month
	}
	let date = d.getDate();
	if (date < 10) {
		date = "0" + date
	}
	let hours = d.getHours();
	if (hours < 10) {
		hours = "0" + hours
	}
	let minutes = d.getMinutes();
	if (minutes < 10) {
		minutes = "0" + minutes
	}
	let seconds = d.getSeconds();
	if (seconds < 10) {
		seconds = "0" + seconds
	}
	let dateTime = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
	return dateTime;
};

/**
 * 时间格式调整
 * @author 晨昱
 * @param {String} data YYYYMMDDhhmmss
 * @return {String} YYYY-MM-DD hh:mm:ss
 */
Vue.prototype.timereplace = function(data) {
	let time = data + "";
	if (time.length == 8) {
		return time.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
	} else if (time.length == 14) {
		return time.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1-$2-$3 $4:$5:$6');
	} else {
		throw new Error('请传入一个8位或者14位的数字');
	}
};
/**
 * 时间格式调整
 * @param {String} data YYYYMMDDhhmmss
 * @return 时间戳 ms
 */
Vue.prototype.timeToStamp = function(data) {
	let time = data + "";
	if (time.length == 8) {
		time = time.replace(/(\d{4})(\d{2})(\d{2})/, '$1/$2/$3');
	} else if (time.length == 14) {
		time = time.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1/$2/$3 $4:$5:$6');
	} else {

	}
	console.log('5555', time)
	let date = new Date(time)
	let aa = date.getTime() + '';
	return aa

};
// 获取路径里面的某个参数
Vue.prototype.$getQueryString = function(path, name) {
	path = decodeURIComponent(path)
	console.log('path', path)
	var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
	if (reg.test(path)) {
		let aa = unescape(RegExp.$2.replace(/\+/g, " "));
		if (aa.indexOf("?") !== -1) {
			let bb = aa.split("?")
			return bb[0]
		}
		console.log('aaa', aa)
		return aa
	}
	return "";
};

Vue.prototype.$WxpRequest = function(res) {
		return new Promise((resolve, reject) => {
				var self = this;
				jweixin1.config({
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: res.data.config.appId, // 必填，公众号的唯一标识
					timestamp: res.data.config.timestamp, // 必填，生成签名的时间戳
					nonceStr: res.data.config.nonceStr, // 必填，生成签名的随机串
					signature: res.data.config.signature, // 必填，签名，见附录1
					jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});
				jweixin1.ready(function() {
					jweixin1.chooseWXPay({
						timestamp: res.data.pay_result
						.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
						nonceStr: res.data.pay_result.nonceStr, // 支付签名随机串，不长于 32 位
						package: res.data.pay_result
						.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
						signType: res.data.pay_result.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
						paySign: res.data.pay_result.paySign, // 支付签名
						success: function(res) {
							// 支付成功后的回调函数
							uni.showToast({
								title: '支付成功'
							})
							resolve(1)
						},
						cancel: function(r) {
							uni.showToast({
								title: '支付取消',
								icon: 'error'
							})
								resolve(2)
						},
						fail: function(res) {
							uni.showToast({
								title: '支付异常',
								icon: 'error'
							})
								resolve(2)
						}
					});
				});
			})

		};
		
		
		
Vue.prototype.$WxShareRequest = function(res,url,title,img,desc) {
		
			// url1 = url1 .replace('#','%23')
			jweixin1.config({
				debug: false,
				// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: res.data.appId,
				// 必填，公众号的唯一标识
				timestamp: res.data.timestamp,
				// 必填，生成签名的时间戳
				nonceStr: res.data.nonceStr,
				// 必填，生成签名的随机串
				signature: res.data.signature,
				// 必填，签名
				jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData'] // 必填，需要使用的JS接口列表
			})
		
			jweixin1.ready(function(res) {
				
				jweixin1.updateTimelineShareData({
					title: title,
					link: url,
					imgUrl: img,
					trigger: function trigger(res) {
						// alert(res);
					},
					success: function success(res) {
						// alert('已分享');
					},
					cancel: function cancel(res) {
						// alert('已取消');
					},
					fail: function fail(res) {
						// alert(2, JSON.stringify(res));
					}
				});
				//分享给朋友
				jweixin1.updateAppMessageShareData({
					title: title,
					desc: desc,
					link: url,
					imgUrl: img,
					trigger: function trigger(res) {
						// alert(res);
					},
					success: function success(res) {
						// alert('已分享');
					},
					cancel: function cancel(res) {
						// alert('已取消');
					},
					fail: function fail(res) {
						// alert(2, JSON.stringify(res));
					}
				});
			})
		
		};
		
  // 输入校验;type==1 不校验小数位数；
  Vue.prototype.checkPriceOut = function(value, type) {
    let checkPlan = '' + value
    checkPlan = checkPlan
      .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
      .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      .replace(/^\./g, '') // 保证第一个为数字而不是.
      .replace('.', '$#$')
      .replace(/\./g, '')
      .replace('$#$', '.')

    if (checkPlan.indexOf('.') < 0 && checkPlan !== '') {
    // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
      checkPlan = parseFloat(checkPlan) + ''
    } else {
      if (type !== 1) {
        if (checkPlan.indexOf('.') >= 0) {
          checkPlan = checkPlan
            .replace(/^()*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
        }
      }
    }
    return checkPlan
  };
    Vue.prototype.checkNum = function(value, type) {

      let checkPlan = '' + value
      checkPlan = checkPlan
        .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
        .replace(/^\./g, '') // 保证第一个为数字而不是.
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
  
      if (checkPlan.indexOf('.') < 0 && checkPlan !== '') {
      // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        checkPlan = parseFloat(checkPlan) + ''
      } else {
        if (type !== 1) {
          if (checkPlan.indexOf('.') >= 0) {
            if (type == 2) {
              checkPlan = checkPlan
                .replace(/^()*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
            } else if (type == 3) {
              checkPlan = checkPlan
                .replace(/^()*(\d+)\.(\d\d\d).*$/, '$1$2.$3') // 只能输入两个小数
            } else if (type == 4) {
              checkPlan = checkPlan
                .replace(/^()*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3') // 只能输入两个小数
						console.log('4444',checkPlan)
            }
          }
        }
      }
      return checkPlan
    };